import time
import tkinter as tk
import sys
import platform
from ui.floating_window import FloatingMicWindow
from ui.tray_icon import create_tray_icon
from voice.microphone import VoiceRecorder
from ws.ws_client import run_async_websocket
from com_utils import setup_logging, run_in_thread

logger = setup_logging()

def main():
    """应用程序主函数"""
    global root
    # 创建UI
    root = tk.Tk()
    root.withdraw()
    FloatingMicWindow(tk.Toplevel(root))
    
    # 创建系统托盘图标
    tray_icon = create_tray_icon()
    if tray_icon:
        run_in_thread(tray_icon.run)
    
    # # 启动录音
    recorder = VoiceRecorder()
    recorder.start()
    
    # # 启动WebSocket连接
    def delayed_start():
        time.sleep(1)  # 等待1秒，让界面先显示
        run_async_websocket()

    run_in_thread(delayed_start)
    
    logger.info("语音助手客户端已启动，等待唤醒...")
    
    # 启动主循环
    root.mainloop()
    recorder.stop()

if __name__ == "__main__":
    # 设置DPI感知
    if platform.system() == "Windows":
        try:
            import ctypes
            ctypes.windll.shcore.SetProcessDpiAwareness(1)
            logger.info("已设置DPI感知")
        except Exception as e:
            logger.error(f"DPI感知设置失败: {str(e)}")
    try:
        main()
    except KeyboardInterrupt:
        logger.info("程序已退出")
        sys.exit(0)
    except Exception as e:
        logger.error(f"致命错误: {str(e)}")
        import traceback
        logger.error(traceback.format_exc())
        sys.exit(1)